﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using KOPLibrary.Forms;

namespace KOPLibrary.Exceptions
{
    public static class ExceptionManager
    {
        public static ApplicationException Manage(Exception exc)
        {
            return Manage(exc, false);
        }
        public static ApplicationException Manage(Exception exc, bool throwException)
        {
            ApplicationException converted = null;
            if (exc is BusinessException)
            {
                converted = (BusinessException)exc;
            }
            else if (exc is TechnicalException)
            {
                converted = (TechnicalException)exc;
            }
            else
            {
                converted = new TechnicalException(exc.Message, exc);
                return converted;
            }
            if (throwException)
                throw converted;
            return converted;
        }

        public static void ShowException(Exception exc)
        {
            ApplicationException converted = Manage(exc);
            string data = GetExceptionData(converted);
            using (ExceptionForm ef = new ExceptionForm(converted,data))
            {
                ef.ShowDialog();
            }
        }

        private static string GetExceptionData(Exception exc)
        {
            Exception e = exc;
            StringBuilder sb = new StringBuilder();
            string temp;
            while (e != null)
            {
                if (string.IsNullOrEmpty(e.StackTrace))
                {
                    e = e.InnerException;
                    continue;
                }
                temp = GetExceptionInnerData(e);
                if (sb.ToString().IndexOf(temp) < 0) sb.AppendLine(temp);
                e = e.InnerException;
            }
            return sb.ToString();
        }

        private static string GetExceptionInnerData(Exception e)
        {
            StringBuilder sb = new StringBuilder();
            {
                sb.AppendLine("Message:"+e.Message);
                sb.AppendLine("StackTrace:" + e.StackTrace);
                if (!string.IsNullOrEmpty(Thread.CurrentPrincipal.Identity.Name)) sb.AppendLine("User:" + Thread.CurrentPrincipal.Identity.Name);
            }
            return sb.ToString();
        }

        
    }
}
